package com.sparrow.socket.udp;


import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

/**
 * 简易 UDP 客户端
 */
public class UdpClient {

    private NioEventLoopGroup group = new NioEventLoopGroup();
    private Bootstrap bootstrap;
    private Channel channel;
    private ChannelHandler channelInitializer;

    public void connect(int localPort) throws InterruptedException {
        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(channelInitializer);

        // 绑定本地端口用于接收消息
        channel = bootstrap.bind(localPort).sync().channel();
    }

    public void setChannelInitializer(ChannelHandler channelInitializer) {
        this.channelInitializer = channelInitializer;
    }

    public void send(String host, int port, ByteBuf buf) {
        DatagramPacket packet = new DatagramPacket(buf, new InetSocketAddress(host, port));
        channel.writeAndFlush(packet);
    }

    public void shutdown() {
        if (channel != null) {
            channel.close();
        }
        group.shutdownGracefully();
    }

}
